﻿using Microsoft.Win32;
using OPCTreeMonitor.ToPLC;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using Brushes = System.Windows.Media.Brushes;
using MessageBox = System.Windows.MessageBox;

namespace OPCTreeMonitor
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            // 初始化窗口但设置不显示在任务栏
            InitializeComponent();
            ShowInTaskbar = false; // 不在任务栏显示
            Visibility = Visibility.Hidden; // 隐藏窗口

            Initialize();

            // 注册应用程序退出事件
            System.Windows.Application.Current.Exit += Current_Exit;
            // 注册会话结束事件（如用户注销）
            SystemEvents.SessionEnding += SystemEvents_SessionEnding;
        }

        private void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
        {
            // 会话结束时的清理工作
        }

        private void Current_Exit(object sender, ExitEventArgs e)
        {
            // 应用程序退出时的清理工作
        }

        private void Initialize()
        {
            OPCMethod.Instance.ReadConfig();
            OPCMethod.Instance.ConncetConfigDb();
            try
            {
                OPCMethod.Instance.Connect();
            }
            catch (Exception ex)
            {
                // 后台运行时可以考虑将错误写入日志而非显示消息框
                OPCMethod.Instance.GetLogByName("App").Error("连接失败", ex);
            }
            plc_Address.Content = OPCMethod.Instance.plcAddress.ToString();

            OPCMethod.Instance.StartUpdate();
            OPCMethod.Instance.InitialLogInstance();
            OPCMethod.Instance.InitializeIlog();

            // 启动后台更新任务
            Task.Run(() => UpdateSomeInfo());

            foreach (var item in OPCMethod.Instance.Plc)
            {
                item.ReconnectStarting += Item_ReconnectStarting;
                item.ReconnectComplete += Item_ReconnectComplete;
                item.Alive += Item_Alive;
            }
        }

        #region 掉线重连
        private void UpdateSomeInfo()
        {
            while (true)
            {
                try
                {
                    foreach (var item in OPCMethod.Instance.Plc)
                    {
                        // 只更新状态到日志，不再更新UI元素
                        //OPCMethod.Instance.GetLogByName("App").Info($"{item.Name} PLC 状态变更为：{item.Connected}");
                    }
                }
                catch (Exception ex)
                {
                    OPCMethod.Instance.GetLogByName("App").Error("更新状态失败", ex);
                }
                Thread.Sleep(200);
            }
        }

        private void Item_ReconnectStarting(object? sender, EventArgs e)
        {
            var name = (sender as IPLC).Name;
            OPCMethod.Instance.GetLogByName("App").Info($"{name} PLC 断线开始重连");
        }

        private void Item_ReconnectComplete(object? sender, EventArgs e)
        {
            var name = (sender as IPLC).Name;
            OPCMethod.Instance.GetLogByName("App").Info($"{name} PLC 重连完成");
        }

        private void Item_Alive(object? sender, string e)
        {
            var name = (sender as IPLC).Name;
            OPCMethod.Instance.GetLogByName("App").Info($"{name} PLC 状态：{e}");
        }
        #endregion

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // 可以根据需要决定是否允许关闭
            // e.Cancel = true; // 如果希望阻止关闭，保持后台运行
        }

        private void Window_StateChanged(object sender, EventArgs e)
        {
            // 移除状态变更处理，因为窗口不会显示
        }
    }
}
